﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using frmPrincipalTestes;

namespace frmPrincipal
{
    public partial class frmCadClientes : Form
    {
        private StandardDBConnection standardDBConnection = new StandardDBConnection();
        private bool isInclusion;

        public frmCadClientes()
        {
            InitializeComponent();
        }

        private void frmCadClientes_Close(object sender, EventArgs e)
        {
            standardDBConnection.cnn.Close();
            standardDBConnection.cnn.Dispose();
        }


        //Funções Auxiliares
        private void CleanFieldsData()
        {
            txtSearchByCode.Enabled = true;
            txtNome.Text = "";
            txtTelefone.Text = "";
            txtEndereco.Text = "";
            txtEmail.Text = "";
        }
        private void CleanFields()
        {

            CleanFieldsData();
            btnDelete.Enabled = false;
            txtCPF.Text = "";
            txtSearchByCode.Text = "";
            txtSearchByCode.Focus();
        }
        private bool IsFieldsFilled()
        {

            bool bPreenchido = true;

            if (txtNome.Text.Trim() == "")
            {
                txtNome.BackColor = Color.LightBlue;
                bPreenchido = false;

            }
            else
                txtNome.BackColor = Color.White;

            if (txtTelefone.Text.Trim() == "")
            {
                txtTelefone.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtTelefone.BackColor = Color.White;

            if (txtEndereco.Text.Trim() == "")
            {
                txtEndereco.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtEndereco.BackColor = Color.White;

            if (txtEmail.Text.Trim() == "")
            {
                txtEmail.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtEmail.BackColor = Color.White;

            return (bPreenchido);
        }

        //Pesquisa de Clientes
        private void SearchCostumer()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText;

            if (!Testes.ValidCPF(txtSearchByCode.Text))
            {
                MessageBox.Show("Forneça um código válido!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            CleanFieldsData();
            this.Cursor = Cursors.WaitCursor;

            sqlCommandText = "SELECT * FROM cliente WHERE cpf = '" + txtSearchByCode.Text + "' ";
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            databaseDataReader = sqlCommand.ExecuteReader();

            if (!databaseDataReader.HasRows)
            {
                isInclusion = true;
                MessageBox.Show("Não Encontrado. O CPF fornecido será usado para ser cadastrado!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtCPF.Text = txtSearchByCode.Text;
                txtSearchByCode.Enabled = false;
            }
            else
            {
                isInclusion = false;
                databaseDataReader.Read();
                txtCPF.Text = databaseDataReader["cpf"].ToString();
                txtNome.Text = databaseDataReader["nome_cliente"].ToString();
                txtTelefone.Text = databaseDataReader["tel_cliente"].ToString();
                txtEndereco.Text = databaseDataReader["end_cliente"].ToString();
                txtEmail.Text = databaseDataReader["email_cliente"].ToString();
                btnDelete.Enabled = true;
            }

            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchCostumer();
        }
        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SearchCostumer();
        }

        //Botões
        private void btnNew_Click(object sender, EventArgs e)
        {
            CleanFieldsData();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;

            if (!IsFieldsFilled())
            {
                MessageBox.Show("Preencha os campos destacados!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            if (isInclusion)
            {
                sqlCommandText = "INSERT INTO cliente (cpf, nome_cliente, tel_cliente, end_cliente, email_cliente)";
                sqlCommandText += " values (";
                sqlCommandText += "'" + txtCPF.Text + "',";
                sqlCommandText += "'" + txtNome.Text + "',";
                sqlCommandText += "'" + txtTelefone.Text + "',";
                sqlCommandText += "'" + txtEndereco.Text + "',";
                sqlCommandText += "'" + txtEmail.Text + "')";
   

            }

            else
            {
                sqlCommandText = "update cliente ";
                sqlCommandText = sqlCommandText + "set nome_cliente = '" + txtNome.Text + "',";
                sqlCommandText = sqlCommandText + " tel_cliente = '" + txtTelefone.Text + "',";
                sqlCommandText = sqlCommandText + " end_cliente = '" + txtEndereco.Text + "',";
                sqlCommandText = sqlCommandText + " email_cliente = '" + txtEmail.Text + "'";
                sqlCommandText = sqlCommandText + " WHERE cpf = '" + txtCPF.Text + "' ";
            }

            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            sqlCommand.ExecuteNonQuery();

            MessageBox.Show("Gravação Efetuada com Sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            CleanFields();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;
            DialogResult resp;

            resp = MessageBox.Show("Confirma a exclusão do registro?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (resp == DialogResult.Yes)
            {
                this.Cursor = Cursors.WaitCursor;

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommandText = "DELETE FROM cliente WHERE cpf = " + txtCPF.Text;
                sqlCommand.CommandText = sqlCommandText;
                sqlCommand.ExecuteNonQuery();

                MessageBox.Show("Exclusão efetuada com sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                CleanFields();
                sqlCommand.Dispose();

                this.Cursor = Cursors.Default;
            }
        
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
